<template>
  <div class="production-management">
    <page>
      <div slot="body">
        <div>
          <div class="line"></div>
          <el-form class="form" label-width="140px" inline>
            <!-- <el-form-item class="form-item" label="设计总需求量：" prop="name">
              <el-input v-model="total" placeholder="" disabled size="small" />
              <i class="el-icon-edit" @click="edit(1)"></i>
            </el-form-item>
            <el-form-item class="form-item" label="设计完成时间：" prop="name">
              <el-input v-model="time" placeholder="" disabled size="small" />
              <i class="el-icon-edit" @click="edit(2)"></i>
            </el-form-item> -->
          </el-form>
        </div>
        <div class="table-operation">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">
            添加
          </el-button>
        </div>
        <el-table :data="tableData" border>
          <el-table-column label="序号" type="index" width="50px"></el-table-column>
          <el-table-column label="检验批次号" prop="batchNumber"></el-table-column>
          <el-table-column show-overflow-tooltip label="物料编码" prop="materialCode" width="170px"></el-table-column>
          <el-table-column show-overflow-tooltip label="物料类型" prop="materialTypeName" width="100px"></el-table-column>
          <el-table-column show-overflow-tooltip label="规格型号" prop="spec" width="100px"></el-table-column>
          <el-table-column show-overflow-tooltip label="计量单位" prop="unitName" width="100px"></el-table-column>
          <el-table-column label="检验时间" width="170px" prop="createTime"></el-table-column>
          <el-table-column label="检验人" width="100px" prop="creator"></el-table-column>
          <el-table-column label="检验结果" width="100px" prop="checkResult">
            <template slot-scope="scope">
              {{ scope.row.checkResult == 0 ? "异常" : "正常" }}
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="note" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="100px">
            <template slot-scope="scope">
              <el-link type="primary" @click="handleEdit(scope.row)" :underline="false">编辑</el-link>
              <el-link type="primary" @click="handleDelete(scope.row)" :underline="false">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="140px">
          <el-form-item label="设计总需求量：" prop="prodNum" v-if="num == 1">
            <el-input v-model="form.prodNum" placeholder="设计总需求量：" />
          </el-form-item>
          <el-form-item label="设计完成时间：" prop="finishDate" v-if="num == 2">
            <el-date-picker v-model="form.finishDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="prodTitle" :close-on-click-modal="false" :visible.sync="openProd" width="800px" append-to-body>
        <el-form ref="prodForm" :model="prodForm" :rules="prodRules" label-width="140px">
          <el-form-item label="检验批次号：" prop="batchNumber">
            <el-input v-model="prodForm.batchNumber" placeholder="请输入物料批次号" />
          </el-form-item>
          <el-form-item label="物料名称：" prop="materialName">
            <el-input v-model="prodForm.materialName" placeholder="请输入物料名称" disabled style="width: calc(100% - 70px)" />
            <el-button type="primary" @click="openInRecord">选择</el-button>
          </el-form-item>
          <el-form-item label="检验结果：" prop="checkResult">
            <el-select v-model="prodForm.checkResult">
              <el-option label="正常" :value="1"></el-option>
              <el-option label="异常" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="外委检测报告" prop="checkResult">
            <!-- <ImageUpload ref="ImageRef"></ImageUpload> -->
            <el-upload
              :action="uploadFileUrl"
              :file-list="fileList"
              :limit="20"
              :on-error="handleUploadError"
              :on-exceed="handleExceed"
              :on-success="handleUploadSuccess"
              :headers="headers"
              accept="pdf"
              class="upload-file-uploader"
              ref="upload"
            >
              <!-- 上传按钮 -->
              <el-button size="mini" type="primary">选取文件</el-button>
            </el-upload>
          </el-form-item>

          <el-form-item label="备注：" prop="note">
            <el-input v-model="prodForm.note" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitProdForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <div slot="footer">
        <el-pagination background :page-size="pageVO.pageSize" :current-page.sync="pageVO.pageNum" :total="pageVO.total"
          :layout="pageOptions.layout" :page-sizes="pageOptions.pageSizes" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </page>
    <WarehousingDialog ref="warehousingRef" @check="handleCheck"></WarehousingDialog>
  </div>
</template>

<script>
import {
  getProdPlan,
  addProdPlan,
  getList,
  getDicts,
  updateProd,
  deleteProd,
} from "@/api/materialCheck";
import { getToken } from "@/utils/auth";
import pageQuery from "../../mixins/pageQuery";
import ImageUpload from "@/components/ImageUpload/index.vue";
import WarehousingDialog from "./warehousingDialog.vue";

export default {
  mixins: [pageQuery],
  components: { ImageUpload, WarehousingDialog },
  data() {
    return {
      form: {
        prodNum: "",
        finishDate: "",
        id: "",
      },
      prodForm: { name: "" },
      open: false,
      openProd: false,
      total: "",
      time: "",
      title: "",
      prodTitle: "",
      tableData: [],
      areaList: [],
      statusOptions: [],
      unitList: [],
      num: 0,
      rules: {
        prodNum: [
          { required: true, message: "设计总需求量不能为空", trigger: "blur" },
        ],
        finishDate: [
          { required: true, message: "设计完成时间不能为空", trigger: "blur" },
        ],
      },
      prodRules: {
        batchNumber: [
          { required: true, message: "请输入检验批次号", trigger: "blur" },
        ],
        materialName: [{ required: true, message: "选择物资名称", trigger: "chage" }],

      },
      uploadFileUrl:
        process.env.VUE_APP_BASE_API + "/steel-arch/client/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
    };
  },
  created() {
    this.getplan();
    this.getTableData();
    const { projectId } = this.$store.getters;
    this.prodForm.projectId = projectId;
    getDicts({ dictType: "sys_tunnel_area" }).then((res) => {
      this.statusOptions = res.data.data;
    });
    getDicts({ dictType: "sys_prod_unit" }).then((res) => {
      this.unitList = res.data.data;
    });
  },
  methods: {
    // 文件个数超出
    handleExceed() {
      this.$message.error(`只允许上传20个文件`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error('上传失败, 请重试');
    },
    // 上传成功回调
    handleUploadSuccess(res, file,fileList) {
      // console.log(res,file)
      this.$message.success('上传成功');
      console.log(fileList)
      this.prodForm.reportLink = JSON.stringify(fileList);
    },
    getplan() {
      const { projectId } = this.$store.getters;
      getProdPlan(projectId).then((res) => {
        this.total = res.data.prodNum;
        this.time = res.data.finishDate;
        (this.form.prodNum = res.data.prodNum),
          (this.form.finishDate = res.data.finishDate);
        this.form.id = res.data.id;
      });
    },
    getTableData() {
      const { projectId } = this.$store.getters;
      const parmas = {
        projectId: projectId,
      };
      getList(parmas).then((res) => {
        this.tableData = res.data.data;
        this.pageVO.total = res.data.total;
      });
    },
    openInRecord() {
      this.$refs.warehousingRef.openHandle();
    },
    handleCheck(row) {
      this.prodForm.materialLogId = row.id;
      this.prodForm.spec = row.spec;
      this.prodForm.materialName = row.materialName;
      this.prodForm.materialCode = row.materialCode;
      this.prodForm.materialTypeName = row.materialTypeName;
      this.prodForm.unitName = row.unitName;
      this.prodForm.actualCount = row.actualCount;
    },
    edit(num) {
      this.open = true;
      if (num == 1) {
        this.title = "设计总需求量修改";
        this.num = 1;
      } else {
        this.title = "设计完成时间修改";
        this.num = 2;
      }
    },
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const { projectId } = this.$store.getters;
          this.form.projectId = projectId;
          addProdPlan(this.form).then((response) => {
            this.$message.success("修改成功");
            this.open = false;
            this.getplan();
            this.getTableData();
          });
        }
      });
    },
    submitProdForm: function () {
      this.$refs["prodForm"].validate((valid) => {
        // this.prodForm.reportLink = this.$refs.ImageRef.getUrl();
        if (valid) {
          if (this.prodForm.id != null) {
            updateProd(this.prodForm).then((response) => {
              this.$message.success("修改成功");
              this.openProd = false;
              this.getTableData();
            });
          } else {
            updateProd(this.prodForm).then((response) => {
              this.$message.success("新增成功");
              this.openProd = false;
              this.getTableData();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.form={prodNum: "",finishDate: "",id: ""}
      this.fileList = []
      // this.$refs.form.resetFields();
      this.openProd = false;
    },
    handleAdd() {
      this.openProd = true;
      this.prodTitle = "添加物料批次";
      this.prodForm = { name: "" };
      this.fileList = []
    },
    handleEdit(row) {
      this.prodTitle = "编辑物料批次";
      this.openProd = true;
      this.prodForm = JSON.parse(JSON.stringify(row));
      const { projectId } = this.$store.getters;
      this.prodForm.projectId = projectId;
      console.log(this.prodForm.reportLink)
      this.fileList=[]
      this.prodForm.reportLink?this.fileList=JSON.parse(this.prodForm.reportLink):''
      // this.$nextTick(() => {
      //   this.$refs.ImageRef.setUrl(row.reportLink);
      // });
    },
    handleDelete(row) {
      this.$confirm(
        '是否确认删除物料类型为"' + row.materialCode + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return deleteProd(row.id);
        })
        .then(() => {
          this.getTableData();
          this.$message.success("删除成功");
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.top {
  display: flex;
  justify-content: flex-start;
  margin: 20px 0;
}

.line {
  width: 8px;
  background: #1890ff;
  margin-right: 15px;
}

.form {
  display: flex;
  margin-top: 10px;

  ::v-deep {
    .el-form-item__label {
      font-weight: normal;
    }
  }
}

.form-item {
  position: relative;
}

.el-icon-edit {
  font-size: 20px;
  right: 10px;
  position: absolute;
  top: 8px;
}
</style>
